<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\MoneyCashLog;
use App\Repository\MoneyCashLogRepository;
use App\Service\MoneyService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiMoneyCashLogController extends BaseController4Restful
{
    /**
     * @Route("/api/moneyCashLogs", name="apiGetMoneyCashLogs",methods={"GET","POST"})
     */
    public function apiGetMoneyCashLogs(MoneyCashLogRepository $repository, Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $MoneyCashLog MoneyCashLog */
                $MoneyCashLog = $this->createEntity($data, MoneyCashLog::class);
                $this->myEm()->persist($MoneyCashLog);
                $this->myEm()->flush();
                return $this->json_out(200, "创建成功", $MoneyCashLog);
            default:
                if (!$page = $this->getParamRequired("page")) {
                    $page = 1;
                }
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page, $total, $limit);
                $list = $repository->findBy(array(), array(), $limit, $offset);
                return $this->json_out(200, "获取成功", $list);
        }
    }

    /**
     * @Route("/api/moneyCashLogs/{id}", name="apiAddMoneyCashLogs",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateMoneyCashLogs(MoneyCashLog $MoneyCashLog, Request $request, MoneyService $moneyService)
    {
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($MoneyCashLog);
                $this->myEm()->flush();
                return $this->json_out(200, "已移除");
            case "PATCH":
            case "PUT":
                $data = $this->getRequestData();
                $startStatus = $MoneyCashLog->getStatus();
                if ($startStatus == 2) {
                    return $this->json_out(201, "资金已退回请勿重复操作");
                }

                /**@var $MoneyCashLog MoneyCashLog */
                $MoneyCashLog = $this->updateEntity($data, MoneyCashLog::class, $MoneyCashLog);

                //驳回时应该吧冻结的金额返回去
                if ($startStatus == 0 && $data["status"] == 2) {
                    $moneyService->userCashFail($MoneyCashLog,$data["message"]);
                }
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($MoneyCashLog);
        $this->myEm()->flush();
        return $this->json_out(200, "操作成功", $MoneyCashLog);
    }
}
